/**
 * Copyright 2018-2019 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.fos.cos;

import java.util.TreeMap;

import org.json.JSONObject;

import com.jianggujin.fos.JFOSLazyException;
import com.jianggujin.fos.JSecurityToken;
import com.jianggujin.fos.JSecurityTokenService;
import com.jianggujin.fos.cos.JCOSConfiguration.JCOSSessionTokenConfiguration;
import com.tencent.cloud.CosStsClient;

import lombok.NonNull;

/**
 * @author jianggujin
 *
 */
public class JCOSSecurityTokenService implements JSecurityTokenService {
    private JCOSConfiguration configuration;

    public JCOSSecurityTokenService(@NonNull JCOSConfiguration configuration) {
        this.configuration = configuration;
    }

    @Override
    public JSecurityToken getSecurityToken() {
        TreeMap<String, Object> config = new TreeMap<String, Object>();

        try {
            // 替换为您的 SecretId
            config.put("SecretId", configuration.getSecretId());
            // 替换为您的 SecretKey
            config.put("SecretKey", configuration.getSecretKey());
            JCOSSessionTokenConfiguration sessionTokenConfiguration = configuration.getSessionTokenConfiguration();
            if (sessionTokenConfiguration.getDurationSeconds() != null) {
                // 临时密钥有效时长，单位是秒，默认1800秒，最长可设定有效期为7200秒
                config.put("durationSeconds", sessionTokenConfiguration.getDurationSeconds());
            }

            if (sessionTokenConfiguration.getBucket() != null) {
                // 换成您的 bucket
                config.put("bucket", sessionTokenConfiguration.getBucket());
            }
            if (sessionTokenConfiguration.getRegion() != null) {
                // 换成 bucket 所在地区,"ap-guangzhou"
                config.put("region", sessionTokenConfiguration.getRegion());
            }

            if (sessionTokenConfiguration.getAllowPrefix() != null) {
                // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子：a.jpg 或者 a/* 或者 * 。
                // 如果填写了“*”，将允许用户访问所有资源；除非业务需要，否则请按照最小权限原则授予用户相应的访问权限范围。
                config.put("allowPrefix", sessionTokenConfiguration.getAllowPrefix());
            }

            if (sessionTokenConfiguration.getAllowActions() != null) {
                // 密钥的权限列表。简单上传、表单上传和分片上传需要以下的权限，其他权限列表请看
                // https://cloud.tencent.com/document/product/436/31923
                // String[] allowActions = new String[] {
                // 简单上传
                // "name/cos:PutObject",
                // 表单上传、小程序上传
                // "name/cos:PostObject",
                // 分片上传
                // "name/cos:InitiateMultipartUpload", "name/cos:ListMultipartUploads",
                // "name/cos:ListParts",
                // "name/cos:UploadPart", "name/cos:CompleteMultipartUpload" };
                config.put("allowActions", sessionTokenConfiguration.getAllowActions());
            }
            // {
            // "Response": {
            // "Credentials": {
            // "Token":
            // "kTRtHpOSOCUzTVWmzlPKweHffXjT9Izo7b61a142d6b56d31c0a7ace4d22bcff3zpbsXKTIrCo43dRRh7bDIKE1ZOE1KRYHEm0KNLjWG_aSF63YoQWchg-l7eXMInxXIc65HqXPjnouCcnQC98J8wEXGfE-X74QQ4kqdZXvvtgJ4yNUyDFRRkgdWtroOk0zQu4Y-h2N6pQU0FyMLSExd3UwGXpNe-CwqgNw9LTMDdz7LwsiQ9QgVCYSBdGaZXH_kOOfbAQFEDzW_8LId2mJG7DNPQMfpvc8pU_uNi0CZuQr686kYm3pLFg09UNHvB5ddn1m5SOBQRfLCK5Esdk4reSu5xw-KdZjJH2U0nZvXPU0JFrRNni1ouUdZiMpXKeZvxiooPMXtyOa_6ZTcdxjOMJfNx6pBOMWnBBJ9ShMV3S6t6AV3QSvCyvwH7dFQBXT9FPY8KK4uqRW168Q2kVt5dDdWqbRHbNg2ofhnUyHRMgYgKhtPFEAj4pJlorgWpyWtGMCGdCqnQkZ-gPOHEG0alJwveCB7CGU-K06cIGA2tZWWVr7wQRF6PrN5hWXnGI-M3hfEy1KX0degBEsjOMD4ORq2OOF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4Ej0pGgvwB-B0WpVO80cFz-131ee7CkYNpqjJljRBUNdvmYHd_QYKQU1WwD8xXrRIQ7d4RsXbzOutl5yb2MxGcpLC5qS62cG6b1XeLSO5h1ZtsFte69kwwTk_fr4zHgqUxrMXjPMRKXKIWFoKGlt6Aycj4ezNkUsoO9pTPCbo0gfMLvWEEvP009_QRI0k6Vby-CKkufjnh3cAGJzpbHUaSxNNp7oN-DDx4O1om4wsiKeMQb-O1y8ZF6HrXYsjaNlJ61EfqHYFGv6tgf_hgGIeppNZMIPvG1YxlTHjykBTxacK1FY0GwtcujQjXY2cFTNFG7hYOgvdJ4ZKzB4HfpB6xIv8v8mFaqZb4dM0ng4KRfQDmq2CUdamJA9MTCU5jTJfNUnGy7M0DCwJMQZRlOmUaVMzKTWkHCnBXEJAgOd3nzYXug3xAKTGKPtcsvoJKM1XawG2-EWPRFAaVn11wThx-SRLcZakynQsu_9VgWiE4qdoSVUGmjExw6vqjqkbiuizZ5zPzzC9cZkwtfoGkdR9DzMmf5etNrGmKJgvJBuNwUWlMJb7m",
            // "TmpSecretId":
            // "AKIDw7dwZbmFSup9CnAOraJ7skiPMybaV3WPP5B4oVMCIL5kLyphV_3IyAHFJ5QMCjE6",
            // "TmpSecretKey": "/lvEo280/AlGt4orjDl9tWLIOMl5nkexS5Pg+xys7ps="
            // },
            // "ExpiredTime": 1547696355,
            // "RequestId": "59a5e07e-4147-4d2e-a808-dca76ac5b3fd"
            // }
            // }
            JSONObject credential = CosStsClient.getCredential(config);
            JSONObject credentials = credential.getJSONObject("Credentials");
            return new JSecurityToken(credentials.getString("TmpSecretId"), credentials.getString("TmpSecretKey"),
                    credentials.getString("Token"), credentials.getLong("ExpiredTime"));
        } catch (Exception e) {
            throw new JFOSLazyException(e.getMessage(), e);
        }
    }

    @Override
    public void destory() {

    }
}
